<template>
  <el-card shadow="hover">
    <!--    查询条件部分-->
    <el-divider content-position="left"><span style="font-weight: bolder;font-size: 18px">查询条件</span></el-divider>
    <div>
      <el-form ref="showForm" label-position="right" label-width="100px">

        <el-row :gutter="24">
          <el-col :span="9">
            <el-form-item label="请假信息：">
              <el-input v-model="queryParma.qjxx" clearable size="small" placeholder="请输入查询的员工名称&请假原因&批准人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请假类型：">
              <el-select
                v-model="queryParma.qjlxbh"
                style="position: relative;left: 5px"
                filterable
                default-first-option
                placeholder="请选择请假类型"
              >
                <el-option
                  key="0"
                  label=""
                  value=""
                />
                <el-option
                  v-for="item in qjlxDictList"
                  :key="item.code"
                  :label="item.value"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" align="right">
            <el-button type="primary" :loading="searchloding" @click="getVacationInfoListPageHandle">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
            <a style="font-size:14px; margin-left: 10px" @click="toggleSearchStatus = !toggleSearchStatus">
              <template v-if="!toggleSearchStatus">
                展开
                <i class="el-icon-arrow-down" />
              </template>
              <template v-else>
                收起
                <i class="el-icon-arrow-up" />
              </template>
            </a>
          </el-col>
        </el-row>
        <template v-if="toggleSearchStatus">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="部门信息：">
                <el-select
                  v-model="queryParma.bmbh"
                  style="position: relative;left: 5px"
                  filterable
                  default-first-option
                  placeholder="请选择请假类型"
                >
                  <el-option
                    key="0"
                    label=""
                    value=""
                  />
                  <el-option
                    v-for="item in departmentInfoList"
                    :key="item.depCode"
                    :label="item.depName"
                    :value="item.depCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否批准：">
                <el-select
                  v-model="queryParma.sfpzbs"
                  style="position: relative;left: 5px"
                  filterable
                  default-first-option
                  placeholder="请选择是否批准"
                >
                  <el-option
                    key="0"
                    label=""
                    value=""
                  />
                  <el-option
                    key="1"
                    label="是"
                    value="1"
                  />
                  <el-option
                    key="2"
                    label="否"
                    value="0"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="员工类型：">
                <el-select
                  v-model="queryParma.yglxbh"
                  style="position: relative;left: 5px"
                  filterable
                  default-first-option
                  placeholder="请选择员工类型"
                >
                  <el-option
                    key="0"
                    label=""
                    value=""
                  />
                  <el-option
                    v-for="item in EmpTypeList"
                    :key="item.employTypeCode"
                    :label="item.employTypeName"
                    :value="item.employTypeCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="9">
              <el-form-item label="请假开始时间范围：" label-width="150px">
                <el-date-picker
                  v-model="timeArray.qjsjksArray"
                  clearable
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                  @change="setChangeTimeHandle('qjkssj')"
                />
                <span>
                  <i style="margin-left: 5px;font-size: 18px;cursor: pointer" class="el-icon-circle-close" @click="setNoneByType('qjkssj')" />
                </span>
              </el-form-item>
            </el-col>

            <el-col :span="9">
              <el-form-item label="请假结束时间范围：" label-width="150px">
                <el-date-picker
                  v-model="timeArray.qjsjjsArray"
                  clearable
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                  @change="setChangeTimeHandle('qjjssj')"
                />
                <span>
                  <i style="margin-left: 5px;font-size: 18px;cursor: pointer" class="el-icon-circle-close" @click="setNoneByType('qjjssj')" />
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="批准时间范围：" label-width="150px">
                <el-date-picker
                  v-model="timeArray.pzsjArray"
                  clearable
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                  @change="setChangeTimeHandle('pzsj')"
                />
                <span>
                  <i style="margin-left: 5px;font-size: 18px;cursor: pointer" class="el-icon-circle-close" @click="setNoneByType('pzsj')" />
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </div>
    <!--    查询查询部分-->
    <div>
      <el-divider content-position="left"><span style="font-weight: bolder;font-size: 18px">请假信息展示</span></el-divider>
      <!--      数据操作按钮-->
      <div style="padding: 10px" align="right">
        <el-button-group>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDeleteBatch">批量删除</el-button>
        </el-button-group>
      </div>

      <el-table
        :data="dataSource"
        :border="true"
        align="center"
        empty-text="暂无数据"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column
          type="index"
          :index="indexMethod"
          label="#"
          width="50"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="员工名称"
          prop="userName"
          fixed="left"
        />
        <el-table-column
          label="年龄"
          align="center"
          prop="employAge"
        />
        <el-table-column
          label="性别"
          align="center"
          prop="gender"
        />
        <el-table-column
          label="员工类型"
          prop="employTypeName"
        />
        <el-table-column
          label="部门名称"
          prop="depName"
          min-width="100"
        />
        <el-table-column
          label="请假开始时间"
          prop="vacateBeginTime"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row.vacateBeginTime | formatdate(scope.row.vacateBeginTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="请假结束时间"
          prop="vacateEndTime"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row.vacateEndTime | formatdate(scope.row.vacateEndTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="请假类型"
          align="center"
          prop="vacateType"
        >
          <template slot-scope="scope">
            {{ getQjlxValueByCode(scope.row.vacateType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="请假原因"
          prop="vacateResion"
          min-width="200"
        />
        <el-table-column
          label="是否批准"
          align="center"
          prop="isApproveFlag"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isApproveFlag"
              v-permission="['超级管理员']"
              :disabled="scope.row.isApproveFlag | checkApproveflag(scope.row.isApproveFlag)"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchHandle(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="批准时间"
          prop="approveTime"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row.approveTime | formatdate(scope.row.approveTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="批准人"
          prop="approverName"
        />
        <el-table-column
          label="操作"
          align="center"
          min-width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div align="center">
        <div style="display: inline-block;width: 60px;height:60px;line-height: 60px;text-align: center;font-size: 15px">
          <span style="text-align: center;line-height: 60px;width: 60px;height:60px;">共{{ dataTotals }}条</span>
        </div>
        <div style="display: inline-block">
          <el-pagination
            :current-page.sync="queryParma.pageIndex"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryParma.pageSize"
            layout="total, sizes, prev,next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <modal
      ref="modals"
      :department-info-list="departmentInfoList"
      :employee-type-list="EmpTypeList"
      :vacation-type-list="qjlxDictList"
      :vacation-info="modifyData"
      @reflushDataHandle="getVacationInfoListPageHandle"
    />
  </el-card>
</template>

<script>
import { dropBatchVacationInfo, getAllVacationInfoPage } from '@/api/ht/yytgl/qjgl/qjxxcx'
const { Message } = require('element-ui')
const { modifyOneVacationInfo } = require('@/api/ht/yytgl/qjgl/qjxxcx')
const { fomatMilsToDate } = require('@/utils/DateUtil')
const { getAllDepartmentInfo } = require('@/api/ht/yytgl/bmgl/bmxxgl')
import Modal from '@/views/ht/yytgl/qjgl/qjxxcx/components/modal'
import { getAllEmpType } from '@/api/ht/yytgl/yggl/yglxgl'
import { getDictsByType } from '@/api/dicts'
const { mapGetters } = require('vuex')
export default {
  name: 'Index',
  components: {
    Modal
  },
  filters: {
    formatdate: function(mils) {
      return fomatMilsToDate(mils)
    },
    checkApproveflag(flag) {
      if (flag === '1') {
        return true
      }
      return false
    }
  },
  computed: {
    ...mapGetters([
      'userinfo'
    ])
  },
  data() {
    return {
      dataSource: [], // 请假信息列表
      dataTotals: 0, // 查询总条数
      modifyData: {}, // 待修改对象信息
      showTimeArray: [], // 回显时间数据
      toggleSearchStatus: false, // 默认是否展开查询条件
      searchloding: false, // 搜索按钮加载
      queryParma: {
        pageIndex: 1,
        pageSize: 5,
        qjxx: '',
        qjkssjBegin: '',
        qjkssjEnd: '',
        qjjssjBegin: '',
        qjjssjEnd: '',
        pzsjBegin: '',
        pzsjEnd: '',
        yglxbh: '',
        bmbh: '',
        qjlxbh: '',
        sfpzbs: ''
      },
      timeArray: { // 时间数组对象
        qjsjksArray: [],
        qjsjjsArray: [],
        pzsjArray: []
      },
      qjlxDictList: [], // 请假类型字典集合
      departmentInfoList: [], // 部门类型信息集合
      EmpTypeList: [], // 员工类型集合
      hasselectedIdArray: [], // 已经选中的部门信息ID数组
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  mounted() {
    this.getDepInfoListHandle() // 获取部门信息列表
    this.getEmpTypeListPageHandle() // 获取员工类型列表
    this.getVacationInfoListPageHandle() // 获取请假信息
    this.getAllQueryDicts() // 获取字典类型信息
  },
  methods: {
    getDepInfoListHandle() {
      this.getDepInfoList()
    },
    getVacationInfoListPageHandle() {
      this.getVacationInfoListPage()
    },
    getEmpTypeListPageHandle() {
      this.getEmpTypeList()
    },
    async getEmpTypeList() {
      const res = await getAllEmpType()
      const data = res.data.main
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.EmpTypeList = data
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    async getDepInfoList() {
      const res = await getAllDepartmentInfo()
      const data = res.data.main
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        this.departmentInfoList = data
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    async getVacationInfoListPage() {
      const res = await getAllVacationInfoPage(this.queryParma)
      const data = res.data.main.dataArray
      const resp = res.data.respOutMsgHeader
      const totals = res.data.main.totalsData
      const currentPage = res.data.main.currentPage
      if (resp.respCode === 200) {
        setTimeout(() => {
          this.searchloding = false
        }, 500)
        this.dataSource = data
        this.dataTotals = totals
        this.queryParma.pageIndex = currentPage
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    getQjlxValueByCode(code) {
      const str = this.checkDictsByCode(this.qjlxDictList, code)
      return str
    },
    checkDictsByCode(dict, code) {
      if (dict) {
        return dict.find(item => item.code === code) ? dict.find(item => item.code === code).value : ''
      } else {
        return null
      }
    },
    indexMethod(index) {
      return index + 1 + (this.queryParma.pageIndex - 1) * this.queryParma.pageSize
    },
    switchHandle(row) {
      this.$confirm('此批假操作不可撤销, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.approveTime = fomatMilsToDate(new Date())
        row.approverName = this.userinfo.username
        this.modifyVacationInfo(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消批假'
        })
        row.isApproveFlag = '0'
      })
    },
    handleAdd() {
      this.$refs.modals.checkModelType('add')
    },
    handleEdit(index, row) {
      // 使用父子传参方式
      this.modifyData = row
      this.$refs.modals.checkModelType('edit')
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields()
      this.queryParma = {
        pageIndex: 1,
        pageSize: 5,
        qjxx: '',
        qjkssjBegin: '',
        qjkssjEnd: '',
        qjjssjBegin: '',
        qjjssjEnd: '',
        pzsjBegin: '',
        pzsjEnd: '',
        yglxbh: '',
        bmbh: '',
        qjlxbh: '',
        sfpzbs: ''
      }
    },
    handleDelete(index, row) {
      const rowIdarray = []
      rowIdarray.push(row.vacateCode)
      this.dropOneVacationInfo(rowIdarray)
    },
    handleDeleteBatch() {
      this.dropBatchVacationInfo()
    },
    getAllQueryDicts() {
      this.getDicts('vacation_type')
    },
    async modifyVacationInfo(rowdata) {
      const res = await modifyOneVacationInfo(rowdata)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: '已批准' || 'Error',
          type: 'success',
          duration: 2 * 1000
        })
        this.getVacationInfoListPageHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    async getDicts(type) {
      if (type === 'vacation_type') {
        const res = await getDictsByType(type)
        console.log(res)
        this.qjlxDictList = res.data.main
      }
    },
    async dropOneVacationInfo(array) {
      const res = await dropBatchVacationInfo(array)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        this.getVacationInfoListPageHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    async dropBatchVacationInfo() {
      const res = await dropBatchVacationInfo(this.hasselectedIdArray)
      const resp = res.data.respOutMsgHeader
      if (resp.respCode === 200) {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        this.getVacationInfoListPageHandle()
      } else {
        Message({
          message: resp.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    handleSizeChange(val) {
      this.queryParma.pageSize = val
      this.getVacationInfoListPageHandle()
    },
    handleCurrentChange(val) {
      this.queryParma.pageIndex = val
      this.getVacationInfoListPageHandle()
    },
    handleSelectionChange(selections) {
      const rowIdArray = []
      for (const selection of selections) {
        rowIdArray.push(selection.vacateCode)
      }
      this.hasselectedIdArray = rowIdArray
    },
    setNoneByType(type) {
      this.timeArray = {}
      if (type === 'qjkssj') {
        this.queryParma.qjkssjBegin = ''
        this.queryParma.qjkssjEnd = ''
      } else if (type === 'qjjssj') {
        this.queryParma.qjjssjBegin = ''
        this.queryParma.qjjssjEnd = ''
      } else if (type === 'pzsj') {
        this.queryParma.pzsjBegin = ''
        this.queryParma.pzsjEnd = ''
      } else {
        this.queryParma.qjkssjBegin = ''
        this.queryParma.qjkssjEnd = ''
        this.queryParma.qjjssjBegin = ''
        this.queryParma.qjjssjEnd = ''
        this.queryParma.pzsjBegin = ''
        this.queryParma.pzsjEnd = ''
      }
    },
    setChangeTimeHandle(str) {
      if (str === 'qjkssj') {
        this.queryParma.qjkssjBegin = this.timeArray.qjsjksArray[0]
        this.queryParma.qjkssjEnd = this.timeArray.qjsjksArray[1]
      } else if (str === 'qjjssj') {
        this.queryParma.qjjssjBegin = this.timeArray.qjsjjsArray[0]
        this.queryParma.qjjssjEnd = this.timeArray.qjsjjsArray[1]
      } else if (str === 'pzsj') {
        this.queryParma.pzsjBegin = this.timeArray.pzsjArray[0]
        this.queryParma.pzsjEnd = this.timeArray.pzsjArray[1]
      } else {
        console.log('参数出错！')
      }
    }
  }
}
</script>

<style scoped>

</style>
